<%@ include file="/common/taglibs.jsp" %>
<c:set var="addCategoryUrl"><spring:url value="/categories/addNewCategory.html"/></c:set>
<c:set var="updateCategoryUrl"><spring:url value="/categories/updateCategory.html"/></c:set>
<c:set var="removeCategoryUrl"><spring:url value="/categories/removeCategory.html"/></c:set>
<c:set var="moveCategoryUrl"><spring:url value="/categories/moveCategory.html"/></c:set>
<head>
	<title><spring:message code="categories.maintainCategories.header"/></title>
	<script type="text/javascript">
	var globalTreeNode = null;
	var globalSelectedNode = null;

	var elNormalMsg = null;
	var elErrorMsg = null;
	
	$(function(){
		elNormalMsg = $("#normalMsg");
		elErrorMsg = $("#errorMsg");
		
		//bind events for tree node
		globalTreeNode = $("#categoriesTree")
	
		.bind("select_node.jstree", function (event, data) {
			putData(data);
		})
		
		.bind("move_node.jstree", function (e, data) {
			data.rslt.o.each(function (i, elNode) {
				var categoryId = $(elNode).attr("id");
			    var parentCategoryId = data.rslt.np.attr("id");
			    var iSequence = 1;
			    $("li#" + parentCategoryId + " > ul > li").each(function(i, el){
			    		    if($(el).attr("id") == categoryId){
			    		    	     iSequence = iSequence + i;
			    		    	     return;
			    		    }
			    });
				
			    $.ajax({
				async : false,
				type: 'POST',
				url: "${moveCategoryUrl}",
				dataType : "json",
				data : {
				    "categoryId" : categoryId,
				    "parentCategoryId" : parentCategoryId,
				    "sequence" : iSequence
				},
				success : function (result) {
					if(result.statusCode == 0){
						$("font", elNormalMsg).text(result.statusMessage);
						elMsg = elNormalMsg;

						//refresh tree UI
						$(data.rslt.oc).attr("id", "node_" + result.id);
						if(data.rslt.cy && $(data.rslt.oc).children("UL").length) {
							data.inst.refresh(data.inst._get_parent(data.rslt.oc));
						}
						
					} else{
						//rollback this moving operation
						$.jstree.rollback(data.rlbk);
						$("font", elErrorMsg).text(result.statusMessage);
						elMsg = elErrorMsg;
					}
					fadeInOut(elMsg);
					cleanFormData();
				}
			    });
			});
		});

		//bind events for buttons
		$("#addCategory").click(function(){
			if(!checkFields()) return false;
			var objData = loadData();
			//showObjectContent(objData);
			doAddNode(objData);
		});
		
		$("#updateCategory").click(function(){
			if(!checkFields()) return false;
			var objData = loadData();
			doUpdateNode(objData);
		});
		
		$("#removeCategory").click(function(){
			if(!checkFields()) return false;
			var objData = loadData();
			doRemoveNode(objData);
		});
	
	});

	//following are utility functions
	/**
	 * Do add new node operation.
	 */
	function doAddNode(objData){
		if(!doAddNodeServer(objData)) return;
		
		var node = globalSelectedNode;
		var newNodeData = new Object();
		var arrDataAttrs = new Array();
		var objDataAttr = null;
		var aLocale = null;
		for(var a = 0; a < LOCALES.length; a++){
			objDataAttr = new Object();
			aLocale = LOCALES[a];
			objDataAttr.language = aLocale;
			objDataAttr.title = objData[aLocale];
			arrDataAttrs.push(objDataAttr);
		}
		newNodeData.data = arrDataAttrs;
		newNodeData.attr = {"id" : objData.categoryId};
		newNodeData.state = "open";
		
		globalTreeNode.jstree("create_node", node, "last", newNodeData, null);
	}

	/**
	 * Do add new node to server operations
	 */
	function doAddNodeServer(objData) {
		var success = false;
		var elMsg = null;
		$.ajax({
			async : false,
			type: 'POST',
			url: "${addCategoryUrl}",
			dataType : "json",
			data : objData,
			success : function (data) {
				if(data.statusCode == 0){
					objData.categoryId = data.newCategoryId;
					$("font", elNormalMsg).text(data.statusMessage);
					elMsg = elNormalMsg;
					success = true;
				} else{
					$("font", elErrorMsg).text(data.statusMessage);
					elMsg = elErrorMsg;
				}
				fadeInOut(elMsg);
			}
		});
		return success;
	}
	
	/**
	 * update node.
	 */
	function doUpdateNode(objData){
		if(!doUpdateNodeServer(objData)) return;
		
		var aLocale = null;
		var aLocaleValue = null;
		var categoryId = objData.categoryId;
		for(var a = 0; a < LOCALES.length; a++){
			aLocale = LOCALES[a];
			aLocaleValue = objData[aLocale];
			globalTreeNode.jstree("rename_node", "#" + categoryId, aLocaleValue, aLocale);
		}
	}

	/**
	 * update node to server.
	 */
	function doUpdateNodeServer(objData) {
		var success = false;
		var elMsg = null;
		$.ajax({
			async : false,
			type: 'POST',
			url: "${updateCategoryUrl}",
			dataType : "json",
			data : objData,
			success : function (data) {
				if(data.statusCode == 0){
					$("font", elNormalMsg).text(data.statusMessage);
					elMsg = elNormalMsg;
					success = true;
				} else{
					$("font", elErrorMsg).text(data.statusMessage);
					elMsg = elErrorMsg;
				}
				fadeInOut(elMsg);
			}
		});
		return success;
	}
	/**
	 * remove node.
	 */
	function doRemoveNode(objData){
		if(!doRemoveNodeServer(objData)) return;
		
		var n = $("#" + objData.categoryId + " li[rel='bookType']").length;
		if(n == 0){
			globalTreeNode.jstree("delete_node", globalSelectedNode);
		} else {
			alert("Has book(s) attached !!");
		}
	}

	/**
	 * remove node to server.
	 */
	function doRemoveNodeServer(objData) {
		var success = false;
		var elMsg = null;
		$.ajax({
			async : false,
			type: 'POST',
			url: "${removeCategoryUrl}",
			dataType : "json",
			data : objData,
			success : function (data) {
				if(data.statusCode == 0){
					$("font", elNormalMsg).text(data.statusMessage);
					elMsg = elNormalMsg;
					success = true;
				} else{
					$("font", elErrorMsg).text(data.statusMessage);
					elMsg = elErrorMsg;
				}
				fadeInOut(elMsg);
			}
		});
		return success;
	}
	
	/**
	 * put selected node data into form.
	 */
	function putData(objData){
		var node = objData.rslt.obj;
		globalSelectedNode = node;
		var elTree = objData.inst;
		switch(node.attr("rel")){
		case "rootCategoryType":
		case "categoryType":
			var id = node.attr("id");
			
			$("#" + id + " > a").each(function(i, el){
				var strText = $.trim($(el).text());
				var strLocales = $(el).attr("class");
				$("#locale4" + strLocales.split(" ",1)).val(strText);
			});
			
			$("#sequence").val(getDataSequence(node));
			$("#categoryId").val(id);   
			$("#parentCategoryId").val(getParentNodeId(elTree, node));
			
			$("#categorySettingForm button").button("option", "disabled", false);
			break;
		case "bookType":
			cleanFormData();
		}
	}
	/**
	 * get UIsequence of the given elNode on the tree UI.
	 */
	function getDataSequence(elNode) {
		var iSequence = 0; 
		var id = $(elNode).attr("id");
		elNode.parent().children().each(function(i, el){
			if($(el).attr("id") == id){
				iSequence = i + 1;
				return iSequence;     
			}
		});
		return iSequence;
	}
	/**
	 * get parent node category id.
	 */
	function getParentNodeId(elTree, elNode) {
		var parentNodeId = null;
		var parentNode = elTree._get_parent(elNode);
		if(parentNode) {
			parentNodeId = parentNode.attr("id");
		}
		return parentNodeId;
	}
	/**
	 * clean form data.
	 */
	function cleanFormData() {
		$("#categorySettingForm input[type='text']").val("");
		$("#categorySettingForm button").button("option", "disabled", true);
	}
	
	/**
	 * check form feilds are whether empty?
	 */
	function checkFields(){
		var pass = true;
		$("input[id^=locale4], input#sequence, input#categoryId").each(function(i, el){
			var val = $.trim($(el).val());
			if(null == val || "" == val){
				alert("At least one Field is not filled");
				$(el).focus();
				pass = false;
				return;
			}
		});
		return pass;
	}
	
	/**
	 * load data object from form.
	 */
	function loadData(){
		var strLocalePrefix = "locale4";
		var objData = new Object();
		$("input[id^=" + strLocalePrefix + "]").each(function(i, el){
			var elObj = $(el);
			var strLocaleName = elObj.attr("id").substr(strLocalePrefix.length);
			objData[strLocaleName] = elObj.val();
		});
		objData["sequence"] = $("input#sequence").val();
		objData["categoryId"] = $("input#categoryId").val();
		objData["parentCategoryId"] = $("input#parentCategoryId").val();
		return objData;
	}
	
	/**
	 * show data object content for debugging.
	 */
	function showObjectContent(objData){
		var str = "[\n";
		var a = 0;
		for(var key in objData){
			if(a != 0){
				str += ",";
			}
			str += key + ":";
			str += objData[key] + "\n";
			a++;
		}
		str += "]";
		alert("objData = " + str);
	}

	/**
	 * fade-in and fade-out given element.
	 */
	function fadeInOut(objSelector) {
		$(objSelector).fadeIn();
		setTimeout(function() {
				$(objSelector).fadeOut();
			}, 5000 );
	}
	
	</script>
</head>
<p><spring:message code="categories.maintainCategories.header"/></p>

<table>
	<tr>
		<td style="height: 500px; width: 400px; overflow: visible; vertical-align: top; border: 1px solid gray;">
			<%@ include file="/WEB-INF/pages/categories/generateCategoriesTree.jsp" %>
		</td>
		<td>
			<table height="100%" style="margin-top: 10px; margin-left: 10px;">
				<tr>
					<td>
					<div class="ui-widget" id="normalMsg" style="display: none;">
						<div style="margin-top: 20px; padding: 0 .7em;" class="ui-state-highlight ui-corner-all"> 
							<div><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-info"></span>
							<font></font></div>
						</div>
					</div>
					<div class="ui-widget" id="errorMsg" style="display: none;">
						<div style="padding: 0 .7em;" class="ui-state-error ui-corner-all"> 
							<div><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-alert"></span> 
							<font></font></div>
						</div>
					</div>
					</td>
				</tr>
				<tr>
					<td style="vertical-align: top;">
					<table id="categorySettingForm">
						<tr>
							<td colspan="2"><h2><spring:message code="categories.maintainCategories.category.header"/></h2></td>
						</tr>
						<c:forEach var="neededLocale" items="${neededLocales}">
							<tr>
								<td><spring:message code="categories.maintainCategories.category.internationalText" arguments="${neededLocale}"/></td>
								<td><input type="text" name="locale4${neededLocale}" id="locale4${neededLocale}"/></td>
							</tr>
						</c:forEach>
						<tr>
							<td><spring:message code="categories.maintainCategories.category.sequence"/></td>
							<td><input type="text" name="sequence" id="sequence" readonly="readonly"/></td>
						</tr>
						<tr>
							<td><spring:message code="categories.maintainCategories.category.id"/></td>
							<td><input type="text" name="categoryId" id="categoryId" readonly="readonly"/></td>
						</tr>
						<tr>
							<td><spring:message code="categories.maintainCategories.category.parent.id"/></td>
							<td><input type="text" name="parentCategoryId" id="parentCategoryId" readonly="readonly"/></td>
						</tr>
						<tr>
							<td colspan="2">
								<button class="aButton" id="addCategory" ><spring:message code="categories.maintainCategories.category.add"/></button>
								<button class="aButton" id="updateCategory" ><spring:message code="categories.maintainCategories.category.update"/></button>
								<button class="aButton" id="removeCategory" ><spring:message code="categories.maintainCategories.category.remove"/></button>
							</td>
						</tr>
					</table>
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>

